package com.ithong;

import com.ithong.realm.CustomerMd5Realm;
import com.ithong.realm.CustomerRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

public class TestCustomerMd5RealmAuthenticator {
    public static void main(String[] args) {
        //创建securityManager
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //设置自定义realm
        CustomerMd5Realm realm = new CustomerMd5Realm();
        //设置realm使用hash凭证器

        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1024);
        realm.setCredentialsMatcher(credentialsMatcher);
        defaultSecurityManager.setRealm(realm);
        //将安全工具类设置安全工具类
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        //通过安全工具类获取subject
        Subject subject = SecurityUtils.getSubject();
        //创建token令牌
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "123");

        try {
            subject.login(token);
            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }

        //认证用户进行授权
        if (subject.isAuthenticated()){
            //基于角色权限控制
            System.out.println(subject.hasRole("admin"));

            //基于多角色权限控制
            System.out.println(subject.hasAllRoles(Arrays.asList("admin", "user")));

            //基于多角色是否具有其中一个角色
            boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "user"));
            for (boolean aBoolean : booleans) {
                System.out.println(aBoolean);
            }

            System.out.println("*************************");
            //基于权限字符串的访问控制 资源标识符 操作 类 资源类型
            System.out.println(subject.isPermitted("user:update:01"));
            System.out.println(subject.isPermitted("product:create:02"));

            //分别具有哪些权限
            boolean[] permitted = subject.isPermitted("user:*:01", "product:*");
            for (boolean b : permitted) {
                System.out.println(b);
            }

            //同时具有那些权限
            System.out.println(subject.isPermittedAll("user:update:01", "product:create:02"));

        }

    }
}
